package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.TravelContent;
import cn.wolfcode.trip.base.mapper.TravelContentMapper;
import cn.wolfcode.trip.base.mapper.TravelMapper;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.ITravelService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelMapper travelMapper;

    @Autowired
    private TravelContentMapper travelContentMapper;

    public PageInfo querForList(TravelQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        return new PageInfo(travelMapper.queryForList(qo));
    }

    public void save(Travel travel) {

        Date date = new Date();

        //设置创建时间

        travel.setCreateTime(date);
        //设置最后更新时间
        travel.setLastUpdateTime(date);
        //设置创建时间和最后更新时间后,执行新增操作
        travelMapper.insert(travel);

        //保存游记内容
        TravelContent travelContent = travel.getTravelContent();
        travelContent.setId(travel.getId());//主键关联
        travelContentMapper.insert(travelContent);
    }

    public Travel getById(Long id) {
        return travelMapper.selectByPrimaryKey(id);
    }

    public void update(Travel travel) {
        //设置最后更新时间
        travel.setLastUpdateTime(new Date());

        //更新时间后,执行修改操作
        travelMapper.updateByPrimaryKey(travel);

        //保存游记内容
        TravelContent travelContent = travel.getTravelContent();

        travelContent.setId(travel.getId());//主键关联

        travelContentMapper.updateByPrimaryKey(travelContent);

    }

    //获取指定的游记内容
    public TravelContent getContentById(Long id) {
        return travelContentMapper.selectByPrimaryKey(id);
    }

    //修改游记状态
    public void changState(Travel travel) {
        //如果是已发布状态,就设置发布时间
        if(travel.getState() == Travel.STATE_RELEASE){
            travel.setReleaseTime(new Date());
        }
        travelMapper.changState(travel);
    }
}
